<?php

namespace addon\lian\model\core\member;

use addon\lian\model\Config;
use addon\lian\model\sqlmodel\LianGoodsModel;
use addon\lian\model\sqlmodel\LianMemberModel;
use addon\lian\model\sqlmodel\LianLevelModel;
use addon\lian\model\sqlmodel\LianPubLineModel;
use addon\lian\model\sqlmodel\OrderGoodsModel;
use app\dict\order\OrderGoodsDict;
use think\facade\Db;
use think\facade\Log;

class CoreLianLevelService
{
    public function getMinLevel($site_id){
        $info = (new LianLevelModel())->where('site_id', $site_id)->where('level_num', 1)->findOrEmpty();
        return $info;
    }


    public function getMaxLevel($site_id){
        $info = (new LianLevelModel())->where('site_id', $site_id)->where('level_num', 2)->findOrEmpty();
        return $info;
    }


    public function getLevelList($site_id){
        $list = (new LianLevelModel())->where('site_id', $site_id)->order('level_num', 'asc')->select();
        return $list;
    }


    /**
     * 链动升级检测
     */
    public static function lianMemberUpgrade($site_id, $lian_member)
    {
        try {
            Log::write('=================ly_lian================进入链动升级检测======lianMemberUpgrade');
            $level_one = (new LianLevelModel())->where('site_id', $site_id)->where('level_num', 1)->findOrEmpty();

            $lian_member['recommend_num'] = Db::name('fenxiao')->where('site_id', $site_id)->where('parent', $lian_member['member_id'])->count();
            
            $lian_member['up_goods_num'] = self::getMemberUpGoosNum($site_id, $lian_member);
            log::write('=================ly_lian================会员ID:' . $lian_member['member_id'] . '推荐人数:' . $lian_member['recommend_num'] . '链动商品购买数:' . $lian_member['up_goods_num']);

            $upgrade_level = [];
            if($level_one['upgrade_type'] == 1){
                if($lian_member['up_goods_num'] >= $level_one['up_goods_num'] && $lian_member['recommend_num'] >= $level_one['recommend_num']){
                    $upgrade_level = $level_one;
                }
            }else {
                if (($level_one['recommend_num'] > 0 && $lian_member['recommend_num'] >= $level_one['recommend_num']) || 
                    ($lian_member['up_goods_num'] >= $level_one['up_goods_num'] && $level_one['up_goods_num'] > 0) ) {
                    $upgrade_level = $level_one;
                }
            } 
            if(empty($upgrade_level)){
                return false;
            }  
            Log::write('=================ly_lian================会员ID:' . $lian_member['member_id'] . '升级等级:' . json_encode($upgrade_level));
            
            if($upgrade_level){
                // (new LianMember())->create(['site_id' => $site_id, 'member_id' => $lian_member_id, 'level_id' => $upgrade_level['level_id']]);
                (new CoreLianMemberAttrService())->autoLianMember($site_id, $lian_member['member_id']);
                return true;
            }   

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }


    public function bossMemberUpgrade($site_id, $lian_member, $order_data){
        try {
            Log::write('=================ly_lian================链动会员升级boss');
            $level_two = (new LianLevelModel())->where(['site_id' => $site_id, 'level_num' => 2])->findOrEmpty();

            $lian_member['recommend_num'] = (new LianMemberModel())->where('site_id', $site_id)->where('pid', $lian_member['member_id'])->count();
            // 获取公排表中的up_pid == parent的会员数量，parent下方滑落的数量
            $down_count = (new LianPubLineModel())->where('site_id', $site_id)->where('up_pid', $lian_member['member_id'])->count();
            $lian_member['recommend_num'] += $down_count;

            $lian_member['up_goods_num'] = $this->getMemberUpGoosNum($site_id, $lian_member);//获取用户升级商品数量

            Log::write('=================ly_lian================链动会员升级boss' . $lian_member['member_id'] . '推荐人数:' . $lian_member['recommend_num'] . '链动商品购买数:' . $lian_member['up_goods_num'] . '');
            
            $upgrade_level = [];
            if($level_two['upgrade_type'] == 1){//升级条件为且关系时，满足条件直接升级
                if (($lian_member['recommend_num'] >= $level_two['recommend_num']) && ($lian_member['up_goods_num'] >= $level_two['up_goods_num'])) {
                    $upgrade_level = $level_two;//
                }
            }else{
                if(($lian_member['recommend_num'] >= $level_two['recommend_num']) || ($lian_member['up_goods_num'] >= $level_two['up_goods_num'])){
                    $upgrade_level = $level_two;//
                }
            }
            if ($upgrade_level) {//升级条件满足时，进行升级操作，并返回升级后的用户信息，否则返回空数组。
                (new CoreLianMemberService())->bossLevelUp($site_id, $lian_member, $order_data);
            }
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }


    public static function getMemberUpGoosNum($site_id, $lian_member){//获取用户升级商品数量
        $goods_ids = (new LianGoodsModel())->where('site_id', $site_id)->where('is_lian', 1)->column('goods_id');//链动商品id集合
        $config = (new Config())->getLianBasicsConfig($site_id);
        $config = $config['data']['value'];

        if ($config['up_way'] == 1) {
            $statusConditions = ['o.order_status' => [OrderGoodsDict::delivery_finish]];
        } else {
            $statusConditions = ['o.order_status' => [OrderGoodsDict::wait_delivery, OrderGoodsDict::delivery, OrderGoodsDict::delivery_finish]];
        }

        $lian_member['up_goods_num'] = (new OrderGoodsModel())->alias('og')
                ->where('og.site_id', $site_id)
                ->where('og.member_id', $lian_member['member_id'])
                ->whereIn('og.goods_id', $goods_ids)
                ->join('order o', 'og.order_id = o.order_id', 'INNER')
                ->whereIn('o.order_status', $statusConditions['o.order_status'])
                ->count(); 
        
        return $lian_member['up_goods_num'];
    }


    public function getLevelByMember($site_id, $member){

        $level = (new LianLevelModel())->where('site_id', $site_id)->where('level_id', $member['level_id'])->findOrEmpty();
        return $level;
    }
}